package com.hrt.test.common;

import java.util.HashMap;

/**
 * 消息队列管理器
 * 
 * @author Administrator
 *
 */
public class MsgQueueManager {

    private HashMap<String, MsgQueue> queueMap = new HashMap<String, MsgQueue>();

    private static volatile MsgQueueManager instance;

    private MsgQueueManager() {

    }

    public static MsgQueueManager getInstance() {
        if (instance == null) {
            synchronized (MsgQueueManager.class) {
                if (instance == null) {
                    instance = new MsgQueueManager();
                }
            }
        }
        return instance;
    }

    public void produce(String queueName, Object msg) {
        prepareQueue(queueName);
        MsgQueue queue = queueMap.get(queueName);
        queue.produce(msg);
    }

    public void consume(String queueName, IMsgListener listener)
            throws QueueHasBeenListenedException, NullQueueListenerException {
        prepareQueue(queueName);
        MsgQueue queue = queueMap.get(queueName);
        System.out.println("注册队列监听，GUID：" + queue.guid);
        queue.consume(listener);
    }

    private void prepareQueue(String queueName) {
        if (!queueMap.containsKey(queueName)) {
            long threadId = Thread.currentThread().getId();
            synchronized (queueMap) {

                System.out.println("线程：" + threadId + ",抢到锁");

                if (!queueMap.containsKey(queueName)) {
                    queueMap.put(queueName, new MsgQueue(queueName));
                }
            }
            System.out.println("线程：" + threadId + ",释放锁");
        }
    }

    public int size(String queueName) {
        int result = 0;
        if (queueMap.containsKey(queueName)) {
            MsgQueue queue = queueMap.get(queueName);
            result = queue.size();
        }
        return result;
    }

}
